package com.kuaimacode.kframework.agent.services.oplog;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.agent.util.SessionUtil;
import com.kuaimacode.kframework.agent.vo.request.HistoryReq;
import com.kuaimacode.kframework.agent.vo.response.HistoryOpLog;
import com.kuaimacode.kframework.mybatis.mapper.index.NoticeMapper;
import com.kuaimacode.kframework.mybatis.mapper.sys.SysOpLogMapper;
import com.kuaimacode.kframework.mybatis.models.index.Notice;
import com.kuaimacode.kframework.mybatis.models.sys.SysOpLog;
import com.kuaimacode.kframework.util.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author anzy
 * @date 2019/06/12
 */
@Service
public class SysOpLogService extends ServiceImpl<SysOpLogMapper, SysOpLog> {

    	/**
    	 *  分页查找所有的数据
    	 * @param pageNum 当前页码，从1开始
    	 * @param pageSize  一页显示多少行
    	 * @return
    	 */
    	public PageInfo<SysOpLog> findAll(int pageNum, int pageSize,String idlist,Long id) {
    		PageHelper.startPage(pageNum, pageSize);
			QueryWrapper queryWrapper = new QueryWrapper();
			queryWrapper.eq("user_id",id);
			queryWrapper.eq("type","0");
			if (StringUtils.isNotEmpty(idlist)){
			    String[] ids = idlist.split(",");
			    List<Integer> integers = new ArrayList<>();
                for (int i = 0; i < ids.length; i++) {
                    integers.add(Integer.parseInt(ids[i]));
                }
                queryWrapper.in("id",integers);
            }
    		List<SysOpLog> datas = baseMapper.selectList(queryWrapper);
    		return new PageInfo<SysOpLog>(datas);
    	}


	/**
	 *  分页查找所有的数据
	 * @param pageNum 当前页码，从1开始
	 * @param pageSize  一页显示多少行
	 * @return
	 */
	public PageInfo<HistoryOpLog> findHistory(int pageNum, int pageSize, Long userId, HistoryReq req) {
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("user_id",userId);
		queryWrapper.eq("type","0");
		if (!(StringUtils.isEmpty(req.getStartDate())&&StringUtils.isEmpty(req.getEndDate()))){
            Optional.ofNullable(req.getEndDate()).ifPresent(str->queryWrapper.le("created_time",str));
            Optional.ofNullable(req.getStartDate()).ifPresent(str->queryWrapper.ge("created_time",str));
        }
		queryWrapper.orderByDesc("created_time");
		List<SysOpLog> datas = baseMapper.selectList(queryWrapper);
        List<HistoryOpLog> historyOpLogs = new ArrayList<>();
        List<HistoryOpLog> newHistory = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(datas)){
            datas.forEach(item->{
                HistoryOpLog opLog = new HistoryOpLog();
                opLog.setHistoryDate(DateUtil.dateToString(item.getCreatedTime(),"yyyy-MM-dd"));
                opLog.setCreatedDt(item.getCreatedTime());
                opLog.setRemark(item.getRemark());
                opLog.setId(item.getId());
                opLog.setUserId(item.getUserId());
                historyOpLogs.add(opLog);
            });
            if (CollectionUtils.isNotEmpty(historyOpLogs)){
                Date now = new Date();
                String nowStr = DateUtil.dateToString(now,"yyyy-MM-dd");
                Map<String,List<HistoryOpLog>> historyGroup = historyOpLogs.stream().collect(Collectors.groupingBy(HistoryOpLog::getHistoryDate));
                historyGroup.forEach((k,v)->{
                    HistoryOpLog opLog = new HistoryOpLog();
                    opLog.setHistoryDate(k);
                    //获得当天日志
                    List<HistoryOpLog> logs = historyGroup.get(k);
//                    opLog.setId();
                    opLog.setUserId(logs.get(0).getUserId());
                    //按照日期排序
                    Collections.sort(logs, new Comparator<HistoryOpLog>() {
                        @Override
                        public int compare(HistoryOpLog o1, HistoryOpLog o2) {
                            return o1.getCreatedDt().compareTo(o2.getCreatedDt());
                        }
                    });
                    Long times = 0L;
                    String dateStr = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
                    StringBuffer buffer = new StringBuffer();
                    if (logs.size()>1){
                        for (int i = 0; i < logs.size(); i++) {
                            if (i==0&&StringUtils.equals("下线",logs.get(0).getRemark())){
                                HistoryOpLog op_0 = logs.get(0);

                                times+= op_0.getCreatedDt().getTime()- DateUtil.stringtoDate(op_0.getHistoryDate()+" 00:00:00","yyyy-MM-dd").getTime();
                            }else if (i==logs.size()-1&&StringUtils.equals("上线",logs.get(logs.size()-1).getRemark())){
                                HistoryOpLog op_last = logs.get(logs.size()-1);
                                if (StringUtils.equals(dateStr,logs.get(0).getHistoryDate())){
                                    times+= System.currentTimeMillis()-op_last.getCreatedDt().getTime();
                                }else{
                                    times+=DateUtil.stringtoDate(dateStr+" 23:59:59","yyyy-MM-dd HH:mm:ss").getTime()-op_last.getCreatedDt().getTime();
                                }
                            }else{
                                HistoryOpLog opHis = logs.get(i);
                                if (StringUtils.equals("下线",opHis.getRemark())){
                                    HistoryOpLog historyOpLog = logs.get(i-1);
                                    times+= opHis.getCreatedDt().getTime()- historyOpLog.getCreatedDt().getTime();
                                }
                            }
                            buffer.append(logs.get(i).getId()).append(",");
                        }
                    }else if (logs.size()==1){
                        HistoryOpLog historyOpLog = logs.get(0);
                        if ("下线".equals(historyOpLog.getRemark())){
                            times  += historyOpLog.getCreatedDt().getTime()-DateUtil.stringtoDate(k+" 00:00:00",DateUtil.FORMAT_ONE).getTime();
                        }else{
                            if (k.equals(nowStr)){
                                times  += now.getTime()- historyOpLog.getCreatedDt().getTime();
                            }else{
                                times  += DateUtil.stringtoDate(k+" 23:59:59",DateUtil.FORMAT_ONE).getTime()- historyOpLog.getCreatedDt().getTime();
                            }
                        }
                        buffer.append(historyOpLog.getId()).append(",");
                    }
                    opLog.setIds(buffer.toString());
                    opLog.setTimes(DateUtil.parseHHMMSS(times));
                    newHistory.add(opLog);
                });
            }
        }
        Collections.sort(newHistory, new Comparator<HistoryOpLog>() {
            @Override
            public int compare(HistoryOpLog o1, HistoryOpLog o2) {
                Date o1Date = DateUtil.stringtoDate(o1.getHistoryDate(),DateUtil.LONG_DATE_FORMAT);
                Date o2Date = DateUtil.stringtoDate(o2.getHistoryDate(),DateUtil.LONG_DATE_FORMAT);
                if (o1Date.getTime()>o2Date.getTime()){
                    return -1;
                }
                if (o1.getHistoryDate().equals(o2.getHistoryDate())){
                    return 0;
                }
                return 1;
            }
        });
		return new PageInfo<HistoryOpLog>(newHistory);
	}


	public List<SysOpLog> findSysOpLog(Long userId,String createdTime){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("type","0");
        if(createdTime!=null&&!"".equals(createdTime)){
            queryWrapper.eq("date_format(created_time,'%Y-%m-%d')",createdTime);
        }
        queryWrapper.orderByAsc("created_time");
        return baseMapper.selectList(queryWrapper);
    }

}
